import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import VueSetupExtend from "vite-plugin-vue-setup-extend";
import vueJsx from "@vitejs/plugin-vue-jsx";
import AutoImportApi from "unplugin-auto-import/vite";
import AutoImportComponent from "unplugin-vue-components/vite";
import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";
import checker from "vite-plugin-checker";
import svgLoader from "vite-svg-loader";
import { svgBuilder } from "./src/plugins/svgBuilder.js";
// @ts-ignore
import tinifyImg from "./src/plugins/tinifyImg.ts";
// @ts-ignore
import proxyAddress from "./src/config/proxyAddress.txt?raw";
// @ts-ignore
import { getNowDate } from "./src/config/system.ts";
const proxyAddressArr = proxyAddress?.split?.("\r\n")?.map((url) => url.trim());
export default defineConfig(async ({ command, mode }) => {
  const config = loadEnv(mode, process.cwd());
  const environment = config.VITE_ENV;
  const isProduction = environment !== "development.dev";
  const proxy_address: any = (env, url = "") => {
    switch (env) {
      case "development.dev":
        return url || config.VITE_URL;
      case "development.test":
        return url || config.VITE_URL;
      case "development.prod":
        return url || config.VITE_URL;
    }
  };
  const getPort: any = (env) => {
    switch (env) {
      case "development.dev":
        return 3001;
      case "development.test":
        return 3003;
      case "development.prod":
        return 3005;
    }
  };
  const port = getPort(environment);
  // 格式化日对象
  console.log("系统更新时间", getNowDate());
  return {
    define: {
      __APP_VERSION__: JSON.stringify("v1.2.5"),
      __APP_BRANCH__: JSON.stringify(mode?.split?.(".")[1]),
      __APP_UPDATE_TIME__: JSON.stringify(getNowDate()),
    },
    envPrefix: "VITE_",
    base: environment === "development.dev" ? "/" : "/",
    productionSourceMap: !isProduction,
    build: {
      outDir: "dist",
      assetsDir: "assets",
      sourcemap: false,
      minify: "terser",
      chunkSizeWarningLimit: 1024 * 10,
      terserOptions: {
        output: {
          comments: true,
        },
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      rollupOptions: {
        output: {
          // 静态资源分类打包
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
          manualChunks: (id) => {
            // 比较大的资源进行分包
            if (id.includes("node_modules")) {
              if (id.includes("ant-design-vue")) return "ant-dsign-vue";
              if (id.includes("@ant-design/icons-vue"))
                return "@ant-design/icons-vue";
              if (id.includes("echarts")) return "echarts";
              if (id.includes("lodash")) return "lodash";
              if (id.includes("moment-timezone")) return "moment-timezone";
              if (id.includes("axios")) return "axios";
              if (id.includes("dayjs")) return "dayjs";
              if (id.includes("pinia")) return "pinia";
              if (id.includes("vod-js-sdk-v6")) return "vod-js-sdk-v6";
            }
          },
        },
      },
    },
    server: {
      https: false,
      open: false,
      cors: true,
      port: port,
      host: "0.0.0.0",
      proxy: {
        "/maps/api": {
          target: proxyAddressArr[0],
          changeOrigin: true,
          rewrite: (path) => path?.replace?.(/^\/maps\/api/, "/maps/api"),
        },
        "/api": {
          target: proxy_address(environment),
          changeOrigin: true,
          rewrite: (path) => path?.replace?.(/^\/api/, ""),
        },
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            hack: `true; @import (reference) "${resolve(
              __dirname,
              "./src/styles/variables/index.less"
            )}";`,
          },
          javascriptEnabled: true,
        },
      },
    },
    resolve: {
      alias: {
        "@": resolve(__dirname, "src"),
        "@user": resolve(__dirname, "src/views/user"),
        "@userList": resolve(__dirname, "src/views/user/list"),
        "@system": resolve(__dirname, "src/views/system"),
        "@home": resolve(__dirname, "src/views/home/list"),
        "@views": resolve(__dirname, "src/views"),
        "@assets": resolve(__dirname, "src/assets"),
        "@components": resolve(__dirname, "src/components"),
        "@layout": resolve(__dirname, "src/components/layout"),
        "@img": resolve(__dirname, "src/assets/img"),
        "@store": resolve(__dirname, "src/store"),
        "@styles": resolve(__dirname, "src/styles"),
        "@theme": resolve(__dirname, "src/styles/theme"),
        "~/": `${resolve(__dirname, "src")}/`,
      },
    },

    plugins: [
      vue(),
      svgLoader(),
      vueJsx(),
      VueSetupExtend(),
      // 自动导入api
      AutoImportApi({
        imports: [
          "vue",
          "vue-router",
          "pinia",
          {
            vue: ["createVNode", "defineExpose", "withModifiers"],
            "ant-design-vue": ["message", "Modal", "notification"],
          },
        ],
        include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/],
        eslintrc: {
          enabled: false,
          filepath: "./.eslintrc-auto-import.json",
          globalsPropValue: true,
        },
        vueTemplate: true,
        dirs: [
          "./src/api",
          "./src/store",
          "./src/config",
          "./src/assets/types",
          "./src/assets/validate",
          "./src/assets/js",
          "./src/assets/hoc",
        ],
        dts: "./src/types/auto-imports.d.ts",
        resolvers: [AntDesignVueResolver()],
      }),
      // 自动导入组件
      AutoImportComponent({
        dts: "./src/types/components.d.ts",
        dirs: [],
        extensions: ["vue", "jsx", "tsx", "ts", "js"],
        // 按需导入组件配置只在模版语法中生效
        resolvers: [
          AntDesignVueResolver({ importStyle: true, resolveIcons: true }),
        ],
      }),
      svgBuilder("./src/assets/icons/ali-svg/"),
      tinifyImg(),
      checker({
        vueTsc: true,
      }),
    ],
  };
});
